package com.tianhe.visitormanagement.server.common;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

/**
 * @author
 */
@Slf4j
@Data
@ChannelHandler.Sharable
@Component
public abstract class TCPHandlerAbstract extends SimpleChannelInboundHandler<ByteBuf> {

    /** 空闲次数 */
    private int idle_count =1;

    /**
     * 读取消息
     *
     * @param ctx
     * @param m
     * @throws Exception
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf m) throws Exception {
        byte[] data = new byte[m.readableBytes()];
        m.readBytes(data);
        String[] strings = bytesToHexStringArr(data);
        parseTcpData(ctx, strings);
    }

    /**
     * 发生异常
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        if (ctx.channel().isActive()) {
            ctx.channel().writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
    }

    /**
     * 客户端主动断开服务端的链接,关闭流
     * */
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        System.out.println(ctx.channel().localAddress().toString() + " 通道不活跃！");
        updateByIp(ctx, 2);
        // 关闭流
        ctx.close();
    }

    /**
     * 客户端主动连接服务端
     * */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        super.channelActive(ctx);
        System.out.println("客户端主动连接服务端");
        updateByIp(ctx, 1);
    }

    /**
     * 超时处理
     * 如果5秒没有接受客户端的心跳，就触发;
     * 如果超过两次，则直接关闭;
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
        if (obj instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) obj;
            if (IdleState.READER_IDLE.equals(event.state())) {  //如果读通道处于空闲状态，说明没有接收到心跳命令
                System.out.println("已经5秒没有接收到客户端的信息了");
                if (idle_count > 2) {
                    System.out.println("关闭这个不活跃的channel");
                    ctx.channel().close();
                }
                idle_count++;
            }
        } else {
            super.userEventTriggered(ctx, obj);
        }
    }

    /**
     * 字节数组转16进制字符串数组
     */
    public static String[] bytesToHexStringArr(byte[] bArr) {
        if (bArr == null) {
            return null;
        }
        String[] strs = new String[bArr.length];
        String sTmp;

        for (int i = 0; i < bArr.length; i++) {
            sTmp = Integer.toHexString(0xFF & bArr[i]);
            if (sTmp.length() < 2) {
                strs[i] = StringUtils.join("0", sTmp);
            } else {
                strs[i] = sTmp;
            }
        }

        return strs;
    }

    public abstract void  parseTcpData(ChannelHandlerContext ctx, String[] strings) throws InterruptedException;

    public abstract void updateByIp(ChannelHandlerContext ctx,long status);
}
